package com.oraro.paygatewaybiz.module.service.Impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.oraro.paygatewaybiz.constant.Constants;
import com.oraro.paygatewaybiz.module.dao.OrderDao;
import com.oraro.paygatewaybiz.module.entity.OrderEntity;
import com.oraro.paygatewaybiz.module.service.OrderService;
import com.oraro.paygatewaybiz.utils.Query;
import com.oraro.uidgeneratorcore.impl.DefaultUidGenerator;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;


@Service("orderService")
public class OrderServiceImpl extends ServiceImpl<OrderDao, OrderEntity> implements OrderService {

    @Autowired
    private DefaultUidGenerator defaultUidGenerator;

    @Override
    public IPage<OrderEntity> queryPage(Map<String, Object> params) {
        IPage<OrderEntity> page = this.page(
                new Query<OrderEntity>(params).getPage(),
                new QueryWrapper<OrderEntity>()
        );

        return page;
    }

    @Override
    public Long createOrder(OrderEntity orderEntity) {
        long orderId= defaultUidGenerator.getUID();
        orderEntity.setOrderId(orderId);
        // 默认未支付状态
        orderEntity.setPayStatus(Constants.PayStatus.UNPAID.getType());
        orderEntity.setFeeType(Constants.FEETYPE);
        orderEntity.setTimeStart(new Date());
        //支付时间默认30min
        orderEntity.setTimeEnd(DateUtils.addMinutes(orderEntity.getTimeStart(), 30));
        this.save(orderEntity);
        return orderId;
    }

    @Override
    public OrderEntity selectByOrderId(Long orderId) {
        return baseMapper.selectByOrderId(orderId);
    }

    @Override
    public Integer getCountByTradeNo(String outTradeNo) {
        return baseMapper.getCountByTradeNo(outTradeNo);
    }

    @Override
    public OrderEntity getByTradeNo(String outTradeNo) {
        return baseMapper.getByTradeNo(outTradeNo);
    }

    @Override
    public void updateOrderChannel(Long orderId, String channelType) {
        baseMapper.updateOrderChannel(orderId, channelType);
    }

    @Override
    public boolean completeOrder(OrderEntity orderEntity) {
        orderEntity.setPayStatus(1);
        orderEntity.setCompleteTime(new Date());
        return this.updateById(orderEntity);
    }


}
